package com.leo.weblogdemo.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 网络请求日志切面
 * </p>
 *
 * @author ：Leo
 * @since ：2021-03-10 9:31
 */
@Aspect
@Component
public class WebLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    /**
     * 定义切面表达式
     * 以 controller 包下定义的所有请求为切入点
     */
    @Pointcut("execution(public * com.leo.weblogdemo.controller..*.*(..))")
    public void webLog(){
        // Do nothing because of pointcut expression.
    }


    /**
     * 再切点之前植入
     * @param joinPoint 切点
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Assert.notNull(attributes, "ServletRequestAttributes is null !");
        HttpServletRequest request = attributes.getRequest();

        // 打印请求相关参数
        logger.info("========================================== Start ==========================================");
        // 打印请求 url
        logger.info("URL            : {}", request.getRequestURL());
        // 打印 Http method
        logger.info("HTTP Method    : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        logger.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        // 打印请求的 IP
        logger.info("IP             : {}", request.getRemoteAddr());
        // 打印请求入参
        Set<Map.Entry<String, String[]>> entries = request.getParameterMap().entrySet();
        for (Map.Entry<String, String[]> entry : entries) {
            logger.info("Request param  : {}", entry.getKey() + " = " + entry.getValue()[0]);
        }
        Object[] args = joinPoint.getArgs();
        if (args.length > 0) {
            logger.info("Request param  : {}", args);
        }

    }

    /**
     * 环绕
     * @param proceedingJoinPoint proceedingJoinPoint
     * @return Object
     * @throws Throwable throwable
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        // 打印出参
        logger.info("Response Args  : {}", result);
        // 执行耗时
        logger.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);

        logger.info("=========================================== End ===========================================");
        // 每个请求之间空一行
        logger.info("");
        return result;
    }
}
